package ua.kharkov.knure.pereverziev.diploma.web.tag;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.log4j.Logger;

/**
 * Place the last JSP address into the current session.
 * 
 * @author A.Pereverziev
 * 
 */
public class LastPageTag extends TagSupport {

	private static final long serialVersionUID = 3978637978739242301L;

	private static final Logger log = Logger.getLogger(LastPageTag.class);

	@Override
	public int doStartTag() throws JspException {
		String lastPage = (String) pageContext.getSession().getAttribute(
				"lastPage");
		log.debug("Session attribute: lastPage --> " + lastPage);

		if (lastPage == null)
			lastPage = "";

		HttpServletRequest request = (HttpServletRequest) pageContext
				.getRequest();

		String requestURI = request.getRequestURI();
		log.trace("Request URI --> " + requestURI);

		String contextPath = request.getContextPath();
		log.trace("Context path --> " + contextPath);

		if (requestURI != null) {
			if (requestURI.startsWith(contextPath))
				lastPage = requestURI.substring(contextPath.length());
		}

		if (lastPage.startsWith("/"))
			lastPage = lastPage.substring(1);

		/*
		 * if (lastPage != null && lastPage.startsWith(contextPath)) lastPage =
		 * requestURI.substring(1, contextPath.length());
		 */
		/*
		 * if ("/".equals(lastPage) || "/login.jsp".equals(lastPage)) lastPage =
		 * contextPath + lastPage;
		 */

		request.getSession().setAttribute("lastPage", lastPage);
		log.debug("Set session attribute: lastPage --> " + lastPage);

		return SKIP_BODY;
	}
}